#include "XmlOuter.h"
#include "ILevel.h"
#include "Record.h"
#include "Common.h"

namespace WLog
{
    XmlOuter::XmlOuter(std::ostream *pOs, const char* szEncode)
        : IOuter(pOs), strEncode(szEncode)
    {
		m_state = HAVE_PARPARED;
		noticeParpareOut();
    }

    XmlOuter::~XmlOuter()
    {
        noticeEndOut();
    }
	
	void XmlOuter::noticeParpareOut()
	{
		if (HAVE_PARPARED == m_state)
		{
			this->out("<?xml version=\"1.0\" encoding=\"" + strEncode + "\" standalone=\"yes\"?>");
			this->outendl();
			this->out("<Context>");
			this->outendl();
			m_state = HAVENT_ENDOUT;
		}        		
	}
	
	void XmlOuter::noticeEndOut()
	{
		if (HAVENT_ENDOUT == m_state)
		{
			this->out("</Context>");
			m_state = HAVE_ENDOUT;
		}		
	}

    bool XmlOuter::outRecord(Record *pRecord, ILevel *pLevel)
    {
        if (!pLevel->callBack_BeforeOut(pRecord, this))
        {
            return false;
        }
        out("\t<Record");
        if (pLevel->bOutName())
        {
            out( " type=\"" + pLevel->getName() + "\"");        
        }
        if (pLevel->bOutDscrp())
        {
            out( " description=\"" + pLevel->getDscrp() + "\"");        
        }
        out(">");
        outendl();

        if (pLevel->bOutFileName())
        {
            outNode("FileName", pRecord->m_strFileName);
        }
        if (pLevel->bOutFuncName())
        {     
            outNode("FunctionName", pRecord->m_strFuncName);
        }
        if (pLevel->bOutLineNo())
        { 	
            outNode("LineNO", l2str(pRecord->m_nLine));
        }
        if (pLevel->bOutTime())
        {
            outNode("RecordTime", pRecord->m_strTime);
        }
        outNode("Message", pRecord->m_strMsg);
        
        out("\t</Record>");
        outendl();
        return pLevel->callBack_AfterOut(pRecord, this);
    }

    void XmlOuter::outNode(string strNodeName, string strContext)
    {
        out("\t\t<"+strNodeName+">");
        out(encode2XmlData(strContext));
        out("</"+strNodeName+">");
        outendl(); 
    }

    string XmlOuter::encode2XmlData(string strContext)
    {//TODO:
        return strContext;
    }
}
